package com.hxzon.aixzsecretary.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.hxzon.aixzsecretary.util.AixzObservable;
import com.hxzon.aixzsecretary.util.AixzSensor;

public class UdpClient extends Thread implements AixzObservable {

	private AixzSensor sensor;

	public UdpClient() {
		sensor = new AixzSensor(this);
	}

	public AixzSensor getSensor() {
		return sensor;
	}

	public void run() {
		DatagramSocket dSocket;
		DatagramPacket inPacket;
		DatagramPacket outPacket;
		InetAddress sAddr;
		byte[] inBuffer = new byte[100];
		byte[] outBuffer;
		String s = System.getProperty("user.name");
		IPuserData ipUserData = new IPuserData();
		String k;

		try {
			dSocket = new DatagramSocket();
			sAddr = InetAddress.getByName("192.168.1.255");// 广播broadcast

			s = "add" + s;

			outBuffer = s.getBytes();
			outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length,
					sAddr, 3001);
			dSocket.send(outPacket);

			while (true) {

				inPacket = new DatagramPacket(inBuffer, inBuffer.length);
				dSocket.receive(inPacket);

				k = new String(inPacket.getData(), 0, 3);
				ipUserData.state = k;
				s = new String(inPacket.getData(), 3, inPacket.getLength() - 3);
				ipUserData.user = s;

				String s2 = (inPacket.getAddress()).toString();
				ipUserData.ip = s2;

				sensor.setData(ipUserData);
				sensor.notifyObservers();
			}

		} catch (IOException e) {
			System.out.println("udpclient run exception");
		}
	}
}